package com.yf.service.im.impl;

import com.yf.dao.im.GroupUserDao;
import com.yf.entity.UserEntity;
import com.yf.enums.ChatTypeEnum;
import com.yf.service.im.MsgSessionService;
import com.yf.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.yf.dao.im.MsgSessionDao;
import com.yf.entity.MsgSessionEntity;

/**
 * 好友请求Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Wed Oct 17 15:08:36 CST 2018
 */
@Service
public class MsgSessionServiceImpl extends BaseServiceImpl<MsgSessionEntity> implements MsgSessionService {
    @Autowired
    private MsgSessionDao msgSessionDao;

    @Autowired
    private GroupUserDao groupUserDao;

    /**内部方法**/

    /**外部方法实现**/
    @Override
    public List<MsgSessionEntity> getAllMsgSession(UserEntity userEntity) {
        //查询和所有好友的会话
        List<MsgSessionEntity> list = new ArrayList<>();
        List<MsgSessionEntity> friedSessionList = msgSessionDao.getByTargetId(userEntity.getId());
        list.addAll(friedSessionList);
        //查询加入的群id
        List<Long> gIds = groupUserDao.getGroupIdsByUserId(userEntity.getId());
        //查询加入的群的session
        if(!gIds.isEmpty()){
            List<MsgSessionEntity> groupSessionList = msgSessionDao.getAllGroupSession(gIds);
            list.addAll(groupSessionList);
        }
        return list;
    }



    //保存消息会话
    @Override
    public void saveMsgSession(MsgSessionEntity msgSessionEntity) {

        MsgSessionEntity session = null;
        if(ChatTypeEnum.SINGLECHAT.getState().equals(msgSessionEntity.getChatType())){
            //先判断好友会话是否存在
            session = msgSessionDao.getFriendSession(msgSessionEntity.getSessionId(),msgSessionEntity.getTargetId());
        }else if(ChatTypeEnum.GROUPCHAT.getState().equals(msgSessionEntity.getChatType())){
            //先判断群会话是否存在
            session = msgSessionDao.getGroupSession(msgSessionEntity.getSessionId());
        }

        if(session == null){  //不存在就保存
            msgSessionDao.save(msgSessionEntity);
        }else { //存在就更新会话
            msgSessionEntity.setId(session.getId());
            msgSessionDao.update(msgSessionEntity);
        }
    }
}
